package ysq.xyg.shop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.service.impl.BaseServiceImpl;
import ysq.xyg.base.util.BaseConstant;
import ysq.xyg.base.util.BaseUtil;
import ysq.xyg.shop.dao.ShopOrderCouponDao;
import ysq.xyg.shop.model.po.ShopItem;
import ysq.xyg.shop.model.po.ShopOrder;
import ysq.xyg.shop.model.po.ShopOrderCoupon;
import ysq.xyg.shop.model.vo.ShopOrderCouponCountVO;
import ysq.xyg.shop.model.vo.ShopOrderCouponExportVo;
import ysq.xyg.shop.model.vo.ShopOrderCouponVo;
import ysq.xyg.shop.service.ShopItemService;
import ysq.xyg.shop.service.ShopOrderCouponService;
import ysq.xyg.shop.service.ShopOrderService;
import ysq.xyg.sys.model.po.SysUser;
import ysq.xyg.web.model.po.WebMember;
import ysq.xyg.web.service.WebMemberService;
import ysq.xyg.wxapi.api.WxApi;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * 商城模块-商品劵管理service实现
 *
 * @author congcong tao
 * @date 2019-4-28 11:19:33
 */
@Service("shopOrderCouponService")
public class ShopOrderCouponServiceImpl extends BaseServiceImpl<ShopOrderCoupon> implements ShopOrderCouponService {

    @Resource
    private ShopOrderService shopOrderService;
    @Resource
    private ShopItemService shopItemService;
    @Resource
    private ShopOrderCouponDao shopOrderCouponDao;
    @Resource
    private WebMemberService webMemberService;

    private ShopOrderCoupon shopOrderCoupon;

    @Autowired
    public void setBaseDao(ShopOrderCouponDao shopOrderCouponDao) {
        this.baseDao = shopOrderCouponDao;
    }

    /**
     * 分页查询
     *
     * @param shopOrderCouponVo 对象
     * @param pageSize 展示数量
     * @param pageNum 当前页面
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-4-28 11:19:33
     */
    public ReturnEntity page(ShopOrderCouponVo shopOrderCouponVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" update_time desc");
        List<ShopOrderCoupon> list = acceptList(shopOrderCouponVo);
        PageInfo<ShopOrderCoupon> page=new PageInfo<ShopOrderCoupon>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    @Override
    public ReturnEntity pageLeft(ShopOrderCouponVo shopOrderCouponVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        List<ShopOrderCoupon> list = shopOrderCouponDao.selectEntityList(shopOrderCouponVo);
        PageInfo<ShopOrderCoupon> page=new PageInfo<ShopOrderCoupon>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    @Override
    public ReturnEntity pageRight(ShopOrderCouponVo shopOrderCouponVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        List<ShopOrderCoupon> list = shopOrderCouponDao.selectEntityRightList(shopOrderCouponVo);
        if (list != null && list.size() > 0) {
            for (ShopOrderCoupon shopOrderCoupon : list) {
                String memberNickName = shopOrderCoupon.getMemberNickName();
                if (StringUtil.isNotEmpty(memberNickName)) {
                    shopOrderCoupon.setMemberNickName(BaseUtil.decodeBase64(memberNickName));
                }
            }
        }
        PageInfo<ShopOrderCoupon> page=new PageInfo<ShopOrderCoupon>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    /**
     * 修改
     *
     * @param shopOrderCouponVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-4-28 11:19:33
     */
    public ReturnEntity addOrUpdate(ShopOrderCouponVo shopOrderCouponVo, SysUser currentUser) {
        boolean isUpate=true;
        if(StrUtil.isEmpty(shopOrderCouponVo.getId())){
            shopOrderCoupon=new ShopOrderCoupon(currentUser);
            isUpate=false;
        }else{
            shopOrderCoupon=selectByPrimaryKey(shopOrderCouponVo.getId());
            if(ObjectUtil.isNull(shopOrderCoupon)){
                return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
            }
            shopOrderCoupon.setUpdateTime(new Date());
            shopOrderCoupon.setUpdateUser(currentUser.getId());
        }
        shopOrderCoupon.setMemberId(shopOrderCouponVo.getMemberId());
        shopOrderCoupon.setItemId(shopOrderCouponVo.getItemId());
        shopOrderCoupon.setItemName(shopOrderCouponVo.getItemName());
        shopOrderCoupon.setBrandName(shopOrderCouponVo.getBrandName());
        shopOrderCoupon.setCatName(shopOrderCouponVo.getCatName());
        shopOrderCoupon.setImage(shopOrderCouponVo.getImage());
        shopOrderCoupon.setQrImage(shopOrderCouponVo.getQrImage());
        shopOrderCoupon.setPrice(shopOrderCouponVo.getPrice());
        shopOrderCoupon.setStatus(shopOrderCouponVo.getStatus());
        shopOrderCoupon.setIssueStatus(shopOrderCouponVo.getIssueStatus());
        shopOrderCoupon.setIssueMessage(shopOrderCouponVo.getIssueMessage());
        shopOrderCoupon.setUploadTime(shopOrderCouponVo.getUploadTime());
        shopOrderCoupon.setCountMoneyStatus("1");
        shopOrderCoupon.setManageTime(shopOrderCouponVo.getManageTime());
        int num=0;
        if(isUpate){
            num=updateByPrimaryKey(shopOrderCoupon);
        }else{
            num=insert(shopOrderCoupon);
        }
        if(num<=0){
            return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
        }
        return new ReturnEntity();
    }
    /**
     * 删除
     *
     * @param id 主键id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author congcong tao
     * @date 2019-4-28 11:19:33
     */
    public ReturnEntity delete(String id, SysUser currentUser) {
        ShopOrderCoupon shopOrderCoupon=selectByPrimaryKey(id);
        if(shopOrderCoupon!=null){
            shopOrderCoupon.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_DELETE);
            shopOrderCoupon.setUpdateTime(new Date());
            shopOrderCoupon.setUpdateUser(currentUser.getId());
            int num=updateByPrimaryKey(shopOrderCoupon);
            if(num>0){
                return new ReturnEntity();
            }
        }
        return new ReturnEntity(BaseConstant.FAIL,BaseConstant.DO_FAIL);
    }

    /**
     * 获取集合
     *
     * @param shopOrderCouponVo 对象
     * @return List<BaseDict> BaseDict集合
     * @author congcong tao
     * @date 2019-4-28 11:19:33
     */
    public List<ShopOrderCoupon> acceptList(ShopOrderCouponVo shopOrderCouponVo){
        Example example = new Example(ShopOrderCoupon.class);
        Example.Criteria criteria = example.createCriteria();
        if(StringUtil.isNotEmpty(shopOrderCouponVo.getRemoveTag())){
            criteria.andEqualTo("removeTag",shopOrderCouponVo.getRemoveTag());
        }
        if(StringUtil.isNotEmpty(shopOrderCouponVo.getQrImage())){
            criteria.andEqualTo("qrImage",shopOrderCouponVo.getQrImage());
        }
        // 1=销售（未入库，可以上架下架）2=下架3=结算4=纠纷，5=入库
        if(StringUtil.isNotEmpty(shopOrderCouponVo.getStatus())){
            criteria.andEqualTo("status",shopOrderCouponVo.getStatus());
        }
        example.setOrderByClause(" update_time desc");
        return shopOrderCouponDao.selectByExample(example);
    }

    @Override
    public Double selectSumPrice(ShopOrderCoupon shopOrderCoupon) {
        return shopOrderCouponDao.selectSumPrice(shopOrderCoupon);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity createOrder(String ids, String description, SysUser sysUser) {
        // ids
        if (StringUtils.isEmpty(ids)) {
            return new ReturnEntity(BaseConstant.FAIL, "传入ids为空");
        }
        String[] idArr = ids.split(",");
        if (idArr == null || idArr.length == 0) {
            return new ReturnEntity(BaseConstant.FAIL, "传入ids为空");
        }
        String orderId = BaseUtil.uId();
        int i = 0;
        double money = 0.0;
        for (String id : idArr) {
            if (StringUtils.isEmpty(id)) {
                continue;
            }
            ShopOrderCoupon shopOrderCoupon = this.selectByPrimaryKey(id);
            if (shopOrderCoupon == null || StringUtils.equals(shopOrderCoupon.getCountMoneyStatus(), "2")) {
                continue;
            }
            shopOrderCoupon.setOrderId(orderId);
            shopOrderCoupon.setCountMoneyStatus("2");
            shopOrderCoupon.setCashStatus("1");
            this.updateByPrimaryKey(shopOrderCoupon);
            i++;
            double price = 0.0;
            if (StringUtils.isNotEmpty(shopOrderCoupon.getPrice())) {
                price = Double.parseDouble(shopOrderCoupon.getPrice());
            }
            money += price;
        }
        if (i == 0) {
            return new ReturnEntity(BaseConstant.FAIL, "优惠券找不到或已打款");
        }
        ShopOrder shopOrder = new ShopOrder(sysUser);
        shopOrder.setId(orderId);
        shopOrder.setNum(String.valueOf(i));
        shopOrder.setMoney(String.valueOf(money));
        shopOrder.setManageTime(DateUtil.date());
        shopOrder.setDescription(description);
        shopOrderService.insert(shopOrder);
        return new ReturnEntity("共打款数：" + i);
    }

    @Override
    public List<ShopOrderCouponCountVO> selectCountList(String memberId) {
        List<ShopOrderCouponCountVO> shopOrderCouponCountVOS = shopOrderCouponDao.selectCountList(memberId);
        return shopOrderCouponCountVOS;
    }

    @Override
    public List<ShopOrderCouponExportVo> selectGroupByMember(ShopOrderCouponVo shopOrderCouponVo) {
        return shopOrderCouponDao.selectGroupByMember(shopOrderCouponVo);
    }

    @Override
    public ReturnEntity pageShowOrder(ShopOrderCouponVo shopOrderCouponVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        List<ShopOrderCouponExportVo> list = shopOrderCouponDao.selectGroupByMember(shopOrderCouponVo);
        PageInfo<ShopOrderCouponExportVo> page=new PageInfo<ShopOrderCouponExportVo>(list);
        return new ReturnEntity(page.getList(),page.getTotal(),page.isHasNextPage());
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity stockIn(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new ReturnEntity(BaseConstant.FAIL, "传参为空");
        }
        String[] idArr = ids.split(",");
        shopOrderCouponDao.stockIn(idArr);
        for (String id : idArr) {
            ShopOrderCoupon shopOrderCoupon = selectByPrimaryKey(id);
            if (shopOrderCoupon == null) {
                continue;
            }
            // 入库后还原数量
            ShopItem shopItem = shopItemService.selectByPrimaryKey(shopOrderCoupon.getItemId());
            if (shopItem != null) {
                String remainderNumStr = shopItem.getRemainderNum();
                if (StringUtils.isNotEmpty(remainderNumStr)) {
                    // 添加成功，需要更改数量
                    int remainderNum = Integer.parseInt(remainderNumStr);
                    shopItem.setRemainderNum(String.valueOf(remainderNum + 1));
                    shopItemService.updateByPrimaryKeySelective(shopItem);
                }
            }
            WebMember webMember = webMemberService.selectByPrimaryKey(shopOrderCoupon.getMemberId());
            String url="/phone/detail?memberId="+webMember.getId()+"&status=1";
            WxApi.sendCoupon(url,webMember.getOpenid(),"您有一个新的商品入库","入库通知",shopOrderCoupon.getItemName(),"点击查看详情");
        }
        return new ReturnEntity();
    }

    @Override
    public ReturnEntity allStockIn() {
        ShopOrderCouponVo shopOrderCouponVo = new ShopOrderCouponVo();
        shopOrderCouponVo.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        // 下架的不管，只入库销售中的
        shopOrderCouponVo.setStatus("1");
        List<ShopOrderCoupon> shopOrderCouponList = this.acceptList(shopOrderCouponVo);
        for (ShopOrderCoupon shopOrderCoupon : shopOrderCouponList) {
            if (shopOrderCoupon == null) {
                continue;
            }
            // 入库后还原数量
            ShopItem shopItem = shopItemService.selectByPrimaryKey(shopOrderCoupon.getItemId());
            if (shopItem != null) {
                String remainderNumStr = shopItem.getRemainderNum();
                if (StringUtils.isNotEmpty(remainderNumStr)) {
                    // 添加成功，需要更改数量
                    int remainderNum = Integer.parseInt(remainderNumStr);
                    shopItem.setRemainderNum(String.valueOf(remainderNum + 1));
                    shopItemService.updateByPrimaryKeySelective(shopItem);
                }
            }
            WebMember webMember = webMemberService.selectByPrimaryKey(shopOrderCoupon.getMemberId());
            String url="/phone/detail?memberId="+webMember.getId()+"&status=1";
            WxApi.sendCoupon(url,webMember.getOpenid(),"您有一个新的商品入库","入库通知",shopOrderCoupon.getItemName(),"点击查看详情");
        }
        return new ReturnEntity();
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity updateCashStatus(String orderId, String memberIds, String cashStatus, String cashMessage) {
        if (StringUtils.isEmpty(memberIds)) {
            return new ReturnEntity(BaseConstant.FAIL, "传参为空");
        }
        ShopOrderCoupon shopOrderCouponRecord = new ShopOrderCoupon();
        shopOrderCouponRecord.setOrderId(orderId);
        List<ShopOrderCoupon> shopOrderCouponList = this.select(shopOrderCouponRecord);
        String title = "";
        if (shopOrderCouponList != null && shopOrderCouponList.size() > 0) {
            title = shopOrderCouponList.get(0).getItemName();
        }
        String[] memberIdArr = memberIds.split(",");
        // 针对未提现的用户操作
        if (StringUtils.equals(cashStatus, "2")) {
            if (memberIdArr != null && memberIdArr.length > 0) {
                for (String memberId : memberIdArr) {
                    // 需要查询member
                    WebMember webMember = webMemberService.selectByPrimaryKey(memberId);
                    if (webMember != null) {
                        String url = "/phone/orderDetail?memberId=" + memberId;
                        WxApi.sendCoupon(url, webMember.getOpenid(), "您有一个新的打款信息", "打款通知", title, "点击查看详情");
                    }
                }
            }
        }
        shopOrderCouponDao.updateCashStatus(orderId, memberIdArr, cashStatus, cashMessage);
        return new ReturnEntity();
    }

    @Override
    public List<ShopOrderCoupon> selectEntityList(ShopOrderCouponVo shopOrderCouponVo) {
        return shopOrderCouponDao.selectEntityList(shopOrderCouponVo);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity updateStatusById(String id, String status) {
        ShopOrderCoupon shopOrderCoupon = this.selectByPrimaryKey(id);
        shopOrderCoupon.setStatus(status);

        if (StringUtils.equals(status, "3")) {
            String price = shopOrderCoupon.getPrice();
            String memberId = shopOrderCoupon.getMemberId();
            WebMember webMember = webMemberService.selectByPrimaryKey(memberId);
            double money = webMember.getMoney();
            if (StringUtils.isNotEmpty(price)) {
                webMember.setMoney(money + Double.parseDouble(price));
            }
            // 结算，信用加1
            int creditScore = webMember.getCreditScore();
            webMember.setCreditScore(creditScore + 1);
            if (StringUtils.isNotEmpty(price)) {
                webMember.setMoney(money - Double.parseDouble(price));
            }
            webMemberService.updateByPrimaryKeySelective(webMember);
        }
        shopOrderCoupon.setUpdateTime(new Date());
        this.updateByPrimaryKeySelective(shopOrderCoupon);
        return new ReturnEntity();
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity updateStatusByIds(String ids, String status) {
        if (StringUtils.isEmpty(ids)) {
            return new ReturnEntity(BaseConstant.FAIL, "传参为空");
        }
        String[] idArr = ids.split(",");
        if (idArr != null && idArr.length > 0) {
            for (String id : idArr) {
                this.updateStatusById(id, status);
            }
        }
        return new ReturnEntity();
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity updateIssueStatusById(String id, String issueStatus, String issueMessage, String issueResultMessage) {
        ShopOrderCoupon shopOrderCoupon = this.selectByPrimaryKey(id);
        shopOrderCoupon.setIssueStatus(issueStatus);
        if (StringUtils.isNotEmpty(issueMessage)) {
            shopOrderCoupon.setIssueMessage(issueMessage);
        }
        if (StringUtils.isNotEmpty(issueResultMessage)) {
            shopOrderCoupon.setIssueResultMessage(issueResultMessage);
        }
        // 1、无纠纷，2、纠纷中，3申诉中 4、纠纷无效，5、纠纷有效
        if (!StringUtils.equals(issueStatus, "1")) {
            shopOrderCoupon.setStatus("4");
        }
        if (StringUtils.equals(issueStatus, "2")) {
            // 纠纷中
            WebMember webMember = webMemberService.selectByPrimaryKey(shopOrderCoupon.getMemberId());
            if (webMember != null) {
                String url = "/phone/complain?memberId=" + webMember.getId() + "&id="+id;
                WxApi.sendCoupon(url, webMember.getOpenid(), "您有一个新的纠纷待处理", "纠纷通知", shopOrderCoupon.getItemName(), "点击查看详情");
            }
        }
        if (StringUtils.equals(issueStatus, "4") || StringUtils.equals(issueStatus, "5")) {
            // 纠纷结果查看
            WebMember webMember = webMemberService.selectByPrimaryKey(shopOrderCoupon.getMemberId());
            if (webMember != null) {
                String url = "/phone/complain?memberId=" + webMember.getId() + "&id="+id;
                WxApi.sendCoupon(url, webMember.getOpenid(), "您有一个新的纠纷结果待查看", "纠纷通知", shopOrderCoupon.getItemName(), "点击查看详情");
            }
        }
        if (StringUtils.equals(issueStatus, "5")) {
            // 处理，将对象金额扣除
            String price = shopOrderCoupon.getPrice();
            String memberId = shopOrderCoupon.getMemberId();
            WebMember webMember = webMemberService.selectByPrimaryKey(memberId);
            double money = webMember.getMoney();
            // 扣除信用分
            int creditScore = webMember.getCreditScore();
            webMember.setCreditScore(creditScore - 2);
            if (StringUtils.isNotEmpty(price)) {
                webMember.setMoney(money - Double.parseDouble(price));
            }
            webMemberService.updateByPrimaryKeySelective(webMember);
        }
        shopOrderCoupon.setUpdateTime(new Date());
        this.updateByPrimaryKeySelective(shopOrderCoupon);
        return new ReturnEntity();
    }
}
